package com.ikun.kunpicturebackend.manager;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.*;
import com.ikun.kunpicturebackend.config.CosClientConfig;
import com.ikun.kunpicturebackend.exception.BusinessException;
import com.ikun.kunpicturebackend.exception.ErrorCode;
import com.ikun.kunpicturebackend.exception.ThrowUtils;
import com.ikun.kunpicturebackend.manager.upload.CosManager;
import com.ikun.kunpicturebackend.model.dto.file.PictureUploadResult;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.model.ciModel.persistence.ImageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

@Service
@Slf4j
@Deprecated
/**
 * 使用PictureUploadTemplate类上传图片
 */
public class FileManager {

    @Resource
    private CosClientConfig cosClientConfig;

    @Resource
    private CosManager cosManager;

    /**
     * 上传图片
     * @param multipartFile 文件
     * @param uploadPathPrefix 上传路径前缀
     * @return
     */
    public PictureUploadResult uploadPicture(MultipartFile multipartFile, String uploadPathPrefix) {
        // 1.校验图片
        validPicture(multipartFile);

        // 2.构造图片上传地址
        // 2.1 16位UUID
        String uuid = RandomUtil.randomString(16);
        // 2.2 获取原始文件名
        String originalFilename = multipartFile.getOriginalFilename();
        // 2.3 上传文件名：yyyy-MM-dd_uuid.文件后缀
        String uploadFileName = String.format("%s_%s.%s", DateUtil.formatDate(new Date()), uuid,
                FileUtil.getSuffix(originalFilename));
        // 2.4 上传路径：/前缀/文件名
        String uploadPath = String.format("/%s/%s", uploadPathPrefix, uploadFileName);

        File file = null;
        try {
            // 3. 创建临时文件
            file = File.createTempFile(uploadPath, null);
            // 3.1 转移文件内容到临时文件
            multipartFile.transferTo(file);

            // 4. 上传图片
            PutObjectResult putObjectResult = cosManager.putObject(uploadPath, file);
            // 4.1 得到返回图片信息
            ImageInfo imageInfo = putObjectResult.getCiUploadResult().getOriginalInfo().getImageInfo();

            // 5. 封装返回结果到PictureUploadResult
            PictureUploadResult uploadResult = new PictureUploadResult();
            // 5.1 计算图片picScale宽高比例：宽/高
            int width = imageInfo.getWidth();
            int height = imageInfo.getHeight();
            Double picScale = NumberUtil.round(width * 1.0 / height, 2).doubleValue();
            // 5.3 封装结果
            uploadResult.setPicWidth(width);
            uploadResult.setPicHeight(height);
            uploadResult.setPicScale(picScale);
            uploadResult.setName(FileUtil.mainName(originalFilename));
            uploadResult.setPicFormat(imageInfo.getFormat());
            uploadResult.setPicSize(FileUtil.size(file));
            uploadResult.setUrl(cosClientConfig.getHost() + "/" + uploadPath);
            return uploadResult;
        } catch (Exception e){
            log.error("图片上传到对象存储失败", e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "图片上传失败");
        } finally {
            deleteTempFile(file);
        }
    }

    /**
     * 校验文件（图片）
     * @param multipartFile 文件（图片）
     */
    public void validPicture(MultipartFile multipartFile) {
        //定义文件的大小和允许的格式
        // 2MB
        final long MAX_MEMORY = 2 * 1024 * 1024L;
        // 允许的文件格式
        final List<String> ALLOW_TYPE = Arrays.asList("jpg", "png", "webp", "jpeg");
        // 校验
        ThrowUtils.throwIf(multipartFile == null, ErrorCode.PARAMS_ERROR, "文件为空");

        // 1. 校验文件大小
        long size = multipartFile.getSize();
        ThrowUtils.throwIf(size > MAX_MEMORY, ErrorCode.PARAMS_ERROR, "文件过大,不能超过2MB");

        // 2. 校验文件格式
        String originalFilename = multipartFile.getOriginalFilename();
        // 获得文件后缀名，扩展名不带“.”
        String suffix = FileUtil.getSuffix(originalFilename);
        ThrowUtils.throwIf(!ALLOW_TYPE.contains(suffix), ErrorCode.PARAMS_ERROR, "文件格式不支持");
    }

    /**
     * 删除临时文件
     * @param file
     */
    public void deleteTempFile(File file){
        if (file == null) {
            return;
        }
        boolean result = file.delete();
        if (!result) {
            log.error("file delete error, filepath = {}", file.getAbsolutePath());
        }
    }


    /**
     * 上传图片（通过url）
     * @param fileUrl 文件路径
     * @param uploadPathPrefix 上传路径前缀
     * @return
     */
    public PictureUploadResult uploadPictureByUrl(String fileUrl, String uploadPathPrefix) {
        // 1.校验图片url
        validPicture(fileUrl);

        // 2.构造图片上传地址
        // 2.1 16位UUID
        String uuid = RandomUtil.randomString(16);
        // 2.2 获取原始文件名
        String originalFilename = FileUtil.mainName(fileUrl);
        // 2.3 上传文件名：yyyy-MM-dd_uuid.文件后缀
        String uploadFileName = String.format("%s_%s.%s", DateUtil.formatDate(new Date()), uuid,
                FileUtil.getSuffix(originalFilename));
        // 2.4 上传路径：/前缀/文件名
        String uploadPath = String.format("/%s/%s", uploadPathPrefix, uploadFileName);

        File file = null;
        try {
            // 3. 创建临时文件
            file = File.createTempFile(uploadPath, null);

            //从url下载图片
            HttpUtil.downloadFile(fileUrl, file);

            // 4. 上传图片
            PutObjectResult putObjectResult = cosManager.putObject(uploadPath, file);
            // 4.1 得到返回图片信息
            ImageInfo imageInfo = putObjectResult.getCiUploadResult().getOriginalInfo().getImageInfo();

            // 5. 封装返回结果到PictureUploadResult
            PictureUploadResult uploadResult = new PictureUploadResult();
            // 5.1 计算图片picScale宽高比例：宽/高
            int width = imageInfo.getWidth();
            int height = imageInfo.getHeight();
            Double picScale = NumberUtil.round(width * 1.0 / height, 2).doubleValue();
            // 5.3 封装结果
            uploadResult.setPicWidth(width);
            uploadResult.setPicHeight(height);
            uploadResult.setPicScale(picScale);
            uploadResult.setName(FileUtil.mainName(originalFilename));
            uploadResult.setPicFormat(imageInfo.getFormat());
            uploadResult.setPicSize(FileUtil.size(file));
            uploadResult.setUrl(cosClientConfig.getHost() + "/" + uploadPath);
            return uploadResult;
        } catch (Exception e){
            log.error("图片上传到对象存储失败", e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "图片上传失败");
        } finally {
            deleteTempFile(file);
        }
    }

    /**
     * 图片url校验
     * @param fileUrl
     */
    private void validPicture(String fileUrl) {
        //非空
        ThrowUtils.throwIf(StrUtil.isBlank(fileUrl), ErrorCode.PARAMS_ERROR, "文件地址不能为空");

        // 1.校验URL格式：通过new URL
        try {
            new URL(fileUrl);
        } catch (MalformedURLException e) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件地址格式不正确");
        }

        // 2.校验URL协议(http/https)
        ThrowUtils.throwIf(!(fileUrl.startsWith("http://") || fileUrl.startsWith("https://")), ErrorCode.PARAMS_ERROR,
                "仅支持HTTP或HTTPS协议的文件路径");

        // 3.发送Head请求，校验图片是否存在
        try (HttpResponse response = HttpUtil.createRequest(Method.HEAD, fileUrl).execute()) {
            // 3.1 创建head请求并执行
            // 3.2 判断是否正常返回
            int status = response.getStatus();
            // 未正常返回直接结束
            if (status != HttpStatus.HTTP_OK) {
                return;
            }

            // 4.校验文件类型
            //获取响应头信息
            String contentType = response.header(Header.CONTENT_TYPE);
            if (StrUtil.isNotBlank(contentType)) {
                // 允许的图片类型
                final List<String> ALLOW_CONTENT_TYPES = Arrays.asList("image/jpeg", "image/jpg", "image/png", "image/webp");
                ThrowUtils.throwIf(!ALLOW_CONTENT_TYPES.contains(contentType.toLowerCase()),
                        ErrorCode.PARAMS_ERROR, "文件类型错误");
            }

            // 5.校验文件大小
            String contentLengthStr = response.header(Header.CONTENT_LENGTH);
            if (StrUtil.isNotBlank(contentLengthStr)) {
                long contentLength = Long.parseLong(contentLengthStr);
                // 2MB
                final long MAX_MEMORY = 2 * 1024 * 1024L;
                ThrowUtils.throwIf(contentLength > MAX_MEMORY, ErrorCode.PARAMS_ERROR, "文件大小不能超过2M");
            }
        } catch (NumberFormatException exception) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件大小格式错误");
        }
    }
}
